<?php 

class Order_model extends CI_Model{
	function __construct()
	{
	    parent::__construct();	    
	}
	//创建机票订单
	public function create_airOrder($data,$user_data)
	{	
		
		$this->load->library('encrypt');
		//产生订单号
		ini_set("date.timezone","Asia/Shanghai");
		$sOrderno=date('ymdGi').sprintf('%04d',rand(0,9999));
		//go_flightinfo :ZH|20110517|ZH9891|08:15|10:40|SZX|PVG|738|0|110|50|V|>9|630.00|
		//0:MU
		//1:20110517
		//2:MU5368
		//3:07:50
		//4:09:50
		//5:SZX
		//6:PVG
		//7:320
		//8:0
		//9:110
		//10:50
		//11:T
		//12:>9
		//13:630.00
		//14:PF/FD
		//15:123 私有政策ID
		
		//16:返点后的价格 628.8
		//17:汇游政策ID AP123
		//18:汇游政策返点 3.5
		$data['go_flightinfo']	=$this->encrypt->decode($data['go_flightinfo']);
		$data['back_flightinfo']	=$this->encrypt->decode($data['back_flightinfo']);
		
		$arflight=explode('|',$data['go_flightinfo']);
		$arbackflight=explode('|',$data['back_flightinfo']);
		$ItineraryName=$arflight[5].'-'.$arflight[6].'-'.$arflight[1];
		
		$blDouble=FALSE;
		$sReturndate=null;
		//设置回程信息
		if($data['back_flightinfo']!="")
		{
			$sReturndate=$arbackflight[1];
			$blDouble=TRUE;
			$ItineraryName=$arflight[5].'-'.$arflight[6].'-'.$arbackflight[6].'-'.$arflight[1];
		}
		//先产生PNR，再产生订单
		//http://210.73.195.74:7899/webabe/webserviceabe.asmx/CreatePNR?
		//Tel=075533398989,075533398898
		//Flightinfo=CTU^SHE^ZH9452^Z^2011-05-09^17:55
		//回程信息格式，SZX,SHA^SHA,SZX^ZH9815,ZH9814^Y,V^2010-11-13,2010-11-17^17:10
		//NameList=熊钰
		//CTList=320624197212171216
		//PTel=15994381825
		////0000,HF9WMM,HKG261
		
		
		$Tel			="075533398989,075533398898";
		$FlightInfo[0]=array(
			"fromport"=> $arflight[5],
			"destport"=> $arflight[6],
			"flightno"=> $arflight[2],
			"classcode"=> $arflight[11],
			"flightdate"=> date('Y-m-d',strtotime($arflight[1])),
			"departtime"=> $arflight[3]		
		);
		
			
		$iTotalFare=0;
		$iTotalPrice=0;
		
		$iTotalFare	=$arflight[13]+$arflight[9]+$arflight[10];
		$iTotalPrice	=$arflight[16]+$arflight[9]+$arflight[10];
		
		if($blDouble)
		{
			
			$FlightInfo[1]=array(
				"fromport"=> $arbackflight[5],
				"destport"=> $arbackflight[6],
				"flightno"=> $arbackflight[2],
				"classcode"=> $arbackflight[11],
				"flightdate"=> date('Y-m-d',strtotime($arbackflight[1])),
				"departtime"=> $arbackflight[3]		
			);
		
			$iTotalFare+=$arbackflight[13]+$arbackflight[9]+$arbackflight[10];
			
			$iTotalPrice+=$arflight[16]+$arbackflight[9]+$arbackflight[10];
		}
		
		$iTotalFare*=$data['TotalAdult'];
		$iTotalPrice*=$data['TotalAdult'];
		
		$iPassenger=count($data['PassengerName']);
		//$NameList="";
		//$CTList="";
		//$PTel="";
		
		$arPassenger=array();
		
		for($i=0;$i< $iPassenger;$i++)
		{
			if($data['PassengerName'][$i]=="")
			{
				$data['PassengerName'][$i]=$data['PFirstName'][$i]."/".$data['PLastName'][$i];
			}
			
			
			//组织字符串
			if($data['PassengerType'][$i]=="1")
			{
				$spName=$data['PassengerName'][$i]."CHD";
			}else
			{
				$spName=$data['PassengerName'][$i];
			}
			
			//国际航班客人输入信息
			if(array_key_exists("PI_userNationality",$data))
			{
				array_push($arPassenger,
					array("Name" => $spName,
						"CardNo" => $data['CTID'][$i],
						"PassengerTel" => $data['PassengerTel'][$i],
						"Nationality" => substr($data['PI_userNationality'][$i],-2,2),
						"PI_userBirth" => $data['PI_userBirth'][$i],
						"PI_userGender" => $data['PI_userGender'][$i],
						"PI_idExpiration" => $data['PI_idExpiration'][$i]
					));
			}else
			{
				
				array_push($arPassenger,
					array("Name" => $spName,
						"CardNo" => $data['CTID'][$i],
						"PassengerTel" => $data['PassengerTel'][$i],
						"Nationality" => "",
						"PI_userBirth" => "",
						"PI_userGender" => "",
						"PI_idExpiration" => ""
					));
			}
			
		}
		
		//国际航班客人输入信息
		if(array_key_exists("PI_userNationality",$data))
		{
			//组织DOCS项
			//CHN/11111/CHN/01JAN75/M/29AUG12/ZHANG/JOHN
			
			$docs="";
			for($i=0;$i< $iPassenger;$i++)
			{
				//组织字符串
				//"CHN/11111/CHN/01JAN75/M/29AUG12/ZHANG/JOHN"
				$docs.=substr($data['PI_userNationality'][$i],-2,2)."/".$data['CTID'][$i].
						"/".substr($data['PI_userNationality'][$i],-2,2)."/".date("dMy",strtotime($data['PI_userBirth'][$i])).
						"/".$data['PI_userGender'][$i]."/".date("dMy",strtotime($data['PI_idExpiration'][$i])).
						"/".$data['PassengerName'][$i].",";
			}
			
			$docs=substr($docs,0,strlen($docs)-1);
		
		}else
		{
			$docs="";
		}
		
		$this->load->Model("Air_model");
		
		
		
		if(array_key_exists("vbook",$user_data))
		{
			$this->load->Model("Virair_model");
			$PNRData=$this->Virair_model->ws_CreatePNR($Tel,$FlightInfo,$arPassenger,$user_data['AgentCode']);
			
			
		}else
		{
			$PNRData=$this->Air_model->ws_CreatePNR($Tel,$FlightInfo,$arPassenger,$user_data['AgentCode']);
		}
		
		
		$fromportName=$this->Air_model->getAirportname_buffer($arflight[5]);
		$destportName=$this->Air_model->getAirportname_buffer($arflight[6]);
		
		//退改签备注
		$this->load->Model("Policy_model");
		$TGQNote = $this->Policy_model->get_TGQNotebyID($arflight[15]);
		
		if($PNRData[0]=="0000")		
		{
			$PNR=$PNRData[1];
		}else
		{
			return array(false,"未产生PNR");
		}
		
		//开始生成订单
		$map_orderdata = array(
              "OrderNo" => $sOrderno,
			"ItineraryName" => $ItineraryName,
			"BookDate" => date("y-m-d H:i:s",time()),
			"TotalPrice" => $iTotalPrice,
			"TotalFare" => $iTotalFare,
			"mainCurrency" => $user_data["mainCurrency"],
			"backmoney" => 0,
			"PayNote" => '',
			"Paid" => 0,
			"SalesName" => $user_data["user_name"],
			"SalesAccount" => $user_data["user_account"],
			"CommisionPaid" => '0',
			"PayType" => '',
			"Status" => '0',
			"Linkman" => $data['LinkMan'],
			"LinkMobile1" => $data['Mobilephone1'],
			"LinkMobile2" => $data['Mobilephone2'],
			"LinkEmail" => $data['Email'],
			"Flightinfo1" => $data['go_flightinfo']."^".$data['back_flightinfo'],
			"fromport" => $arflight[5],
			"destport" => $arflight[6],
			"fromportName" => $fromportName,
			"destportName" =>  $destportName,
			"departdate" => $arflight[1],
			"ReturnDate" => $sReturndate,
			"airline" => $arflight[2],			
			"PNR" => $PNR,
			"PolicyID" => $arflight[17],
			"rebate" => $arflight[18],
			"TGQNote" => $TGQNote,
			"TotalPassenger" => $data['TotalAdult'],
			"lPessengerName" => implode(",",$data['PassengerName']),
			"AgentCode" => $user_data['AgentCode'],
			"AgentName" => $user_data['AgentName'],
			"htOperAccount" => '',
			"htoperName" => '',
			"htStatus" => ''
            );
          
		
          $bsi_bookairdata=array(
	          "OrderNo" => $sOrderno,
			"fromport" => $arflight[5],
			"destport" => $arflight[6],
			"flightdate" => $arflight[1],
			"flightNumber" => $arflight[2],
			"FlightTime" => $arflight[3],
			"ArriveTime" => $arflight[4],
			"class" => $arflight[11],
			"price" =>  $arflight[13],
			"note" => $TGQNote,
			"PNR" => $PNR,
			"OilFee" =>  $arflight[9],
			"AirportFee" =>  $arflight[10],
			"discount" => 0,
			"FromPortName" => $fromportName,
			"DestPortName" => $destportName,
			"PlaneType" => $arflight[7],
			"Airline" => $arflight[0],
			"bookNote" => '',
			"TGQNote" => $TGQNote,
			"cost" =>  $arflight[16],
			"PolicyID" => $arflight[17],
			"rebate" => $arflight[18],
			"stopped" => $arflight[8]
          );
          //$this->db->query('SET NAMES utf8');
          $this->db->trans_start();        
          //插入订单表map_order
		$this->db->insert('map_order', $map_orderdata);
		//插入客人信息表bok_cps
		$iPassenger=count($data['PassengerName']);
		for($i=0;$i< $iPassenger;$i++)
		{
			//国际航班客人输入信息
			if(array_key_exists("PI_userNationality",$data))
			{
				$Note2=json_encode(
					array("PassengerName"=> $data['PassengerName'][$i],
						"PassengerType"=> $data['PassengerType'][$i],
						"PassengerTel"=> $data['PassengerTel'][$i],
						"PI_userNationality"=> $data['PI_userNationality'][$i],
						"PI_userGender"=> $data['PI_userGender'][$i],
						"PI_userBirth"=> $data['PI_userBirth'][$i],
						"CTID"=> $data['CTID'][$i],
						"CTType"=> $data['CTType'][$i],
						"PI_idExpiration"=> $data['PI_idExpiration'][$i],
						"PI_passType"=> $data['PI_passType'][$i]
					)
				);
			}else
			{
				$Note2="";	
			}
			$book_cpsdata=array(
		          "OrderNo" => $sOrderno,
				"Serial" => $data['Serrial'][$i],
				"Name" => $data['PassengerName'][$i],
				"Type" => $data['PassengerType'][$i],
				"CertificateType" => $data['CTType'][$i],
				"CTID" => $data['CTID'][$i],
				"PPID" => $data['PassengerTel'][$i],
				"HKID" => "",
				"Note" => "",
				"note2" => $Note2
			);
			$this->db->insert('bok_cps', $book_cpsdata);
		}
		
		//插入机票信息表bsi_bookairticket
		$this->db->insert('bsi_bookairticket', $bsi_bookairdata);
		
		$this->db->trans_complete();
		
		//写日志
		$this->write_orderlog($sOrderno,"Create Order","",$user_data);
		
		//发送邮件
		$this->sendmail($data['Email'],"book Success","New Order No is $sOrderno,The PNR:".$PNR);
		
		//往汇游导入订单
		if($user_data["isrebate"])
		{
			$this->load->model("Huitrip_model");
			$huitripdata=array(
				"MobilePhone" => $data['Mobilephone1'],
				"Linkman" => $data['LinkMan'],
				"PNR" => $PNR,
				"Fax" =>"",
				"Address" =>"",
				"tel1" => $data['Mobilephone2'],
				"PolicyID" => $arflight[17]
			);
			
			$this->Huitrip_model->hy_bookOrderbyPNR($sOrderno,$huitripdata);
		}
		
		
		return array(true,$sOrderno);
		

	}
	
	//获取机票信息
	public function get_airOrder($sOrderno,$user_data)
	{
		
		
		$sql="Select BookDate,TotalPrice,TotalPassenger,Linkman,LinkMobile1,LinkMobile2,LinkEmail,".
			"Flightinfo1,fromportName,destportName,departdate,returndate,".
			"mainCurrency,Status,TotalCost,PNR,TGQNote,interface_result,backmoney From map_order".
			" Where OrderNo='$sOrderno' ";
		
		//后台查询
		if(array_key_exists("uadmin_account",$user_data))
		{
			$useraccount=$user_data["uadmin_account"];
			$sql.=" And AgentCode='$useraccount'";
		}else if($user_data["user_account"]=="guest")
		{
			$useraccount=$user_data["AgentCode"];
			$sql.=" And AgentCode='$useraccount'";
		}
		else
		{
			$useraccount=$user_data["user_account"];
			$sql.=" And SalesAccount='$useraccount'";
		}
		//echo $sql;
		//获取订单信息
		
		$query = $this->db->query($sql);
		if ($query->num_rows()> 0)
		{
			$objorder = $query->row();
		}else
		{
			exit("error orderno");
		}

		//获取客人信息
		$sql="Select Type,Name,CertificateType,CTID,PPID,HKID,PassengerID,note2 From bok_cps".
			" Where OrderNo='$sOrderno'";
		
		$query = $this->db->query($sql);
		if ($query->num_rows()> 0)
		{
			$objcps = $query->result();
		}
		
		return array(
			"order" => $objorder,
			"passlist" => $objcps,
		);
	}
	
	//订单查询
	public function query_airOrder($querydata,$user)
	{
		$sql="Select Orderno,BookDate,departdate,fromport,destport,TotalPrice,Status,mainCurrency".
			" From map_order ".
			" Where 1 ";
			
		if($querydata["OrderNo"]!="")
		{
			$sql.=" And OrderNo like '%".$querydata['OrderNo']."%'";
		}
		if($querydata["PassengerName"]!="")
		{
			$sql.=" And lPessengerName like '%".$querydata['PassengerName']."%'";
		}
		
		if($querydata["bookdate1"]!="")
		{
			$sql.=" And DateDiff('".Date("Y-m-d",strtotime($querydata["bookdate1"]))."',BookDate)<=0";
		}
		
		if($querydata["bookdate2"]!="")
		{
			$sql.=" And DateDiff(BookDate,'".Date("Y-m-d",strtotime($querydata["bookdate2"]))."')<=0";
		}
		if($user=="guest")
		{
			$sql.=" And LinkEmail='".$querydata['Email']."'";
			$sql.=" And Linkman='".$querydata['LinkMan']."'";
		}else
		{
			$sql.=" And SalesAccount='$user'";
		}
		$sql.=" Order by BookDate desc";
		
		$query = $this->db->query($sql);
		
		$myorder = $query->result();
		
		return $myorder;
	}
	
	//邮件发送
	public function sendmail($tomail,$subject,$message)
	{
		if($this->session->userdata("WEB_AgentCode")=="flyguam")
		{
			$this->sendNotifyEmail($subject,$message,$this->session->userdata("WEB_AgentCode"));
		}
		return true;
		$this->load->library('email');
		
		
		$smtpinfo	=$this->session->userdata("WEB_smtpinfo");
		//$smtpinfo="smtp.163.com||25||shzwr||Myc6848145||shzwr@163.com||张卡米";
		//echo $smtpinfo;
		$arsmpt	=explode("||",$smtpinfo);
		
		$config['protocol'] = 'smtp';
		$config['smtp_host']=$arsmpt[0];
		$config['smtp_user']=$arsmpt[2];
		$config['smtp_pass']=$arsmpt[3];
		$config['smtp_port']=$arsmpt[1];
		
		$this->email->initialize($config);

		$this->email->from($arsmpt[4],$arsmpt[5]);
		$this->email->to($tomail); 
		
		$this->email->subject($subject);
		$this->email->message($message); 
		
		//echo $this->email->print_debugger();
		//exit();
		return $this->email->send();
	}
	public function sendNotifyEmail($subject,$message,$AgentCode)
	{
		$this->load->library('email');
		
		
		//$smtpinfo	=$this->session->userdata("WEB_smtpinfo");
		//$smtpinfo="smtp.exmail.qq.com||465||zhangweirong||848145||zhangweirong@jzinfo.sh.cn||system";
		$smtpinfo="smtp.163.com||25||shzwr||Myc6848145||shzwr@163.com||张卡米";
		
		//$tomail="398512708@qq.com";
		
		//获取EMAIL信息
		$this->db->select("NotifyEmail");
		$query =$this->db->get_where("sys_user",array('AgencyCode' => $AgentCode));
		
		$NotifyEmail=$query->row()->NotifyEmail;
		if($NotifyEmail=="")
		{
			return;	
		}
		$tomail=explode("||",$NotifyEmail);
		
		$arsmpt	=explode("||",$smtpinfo);
		
		$config['protocol'] = 'smtp';
		$config['smtp_host']=$arsmpt[0];
		$config['smtp_user']=$arsmpt[2];
		$config['smtp_pass']=$arsmpt[3];
		$config['smtp_port']=$arsmpt[1];
		
		$this->email->initialize($config);

		$this->email->from($arsmpt[4],$arsmpt[5]);
		$this->email->to($tomail); 
		
		$this->email->subject($subject);
		$this->email->message($message); 
		
		return $this->email->send();
	}
	
	//查询后台订单
	public function query_adminorder($querydata,$adminuser)
	{
		$sql="Select *".
			" From map_order ".
			" Where AgentCode='".$adminuser['uadmin_account']."' ";
			
		if($querydata["orderno"]!="")
		{
			$sql.=" And OrderNo like '%".$querydata['orderno']."%'";
		}
		if($querydata["passname"]!="")
		{
			$sql.=" And lPessengerName like '%".$querydata['passname']."%'";
		}
		
		if($querydata["BookDate1"]!="")
		{
			$sql.=" And DateDiff('".$querydata["BookDate1"]."',BookDate)<=0";
		}
		
		if($querydata["BookDate2"]!="")
		{
			$sql.=" And DateDiff(BookDate,'".$querydata["BookDate2"]."')<=0";
		}
		$sql.=" Order by BookDate desc";
		$query = $this->db->query($sql);
		
		return $query->result();
		
	}
	
	//更新订单状态
	public function update_orderstatus($data,$adminuser)
	{
		$updatdata=array(
			"Status" => $data["status"]
		);
		
		
		$lognote="";
		$arOrderStatus=$this->config->item("OrderStatus");
		//查询原始订单状态
		$query=$this->db->query("Select Status From map_order Where OrderNo='".$data["Orderno"]."'");
		if ($query->num_rows() > 0)
		{
		   $lognote="From ".$arOrderStatus[$query->row()->Status]." To ".$arOrderStatus[$data["status"]];
		}
		
		if($data["status"]=="4")
		{
			$updatdata["backmoney"]=$data["refundFee"];
			$lognote.="refundFee:".$updatdata["backmoney"];
		}
		
		
		$this->db->where('OrderNo ', $data["Orderno"]);
		$this->db->where('AgentCode ', $adminuser["uadmin_account"]);
		
		$this->db->update('map_order', $updatdata); 
		
		//记录日志
		$user_data=array(
			"AgentCode" => $adminuser["uadmin_account"],
			"AgentName" => $adminuser["uadmin_name"],
			"user_account" => "admin",
			"user_name" => "admin"
		);
		
		$this->write_orderlog($data["Orderno"],"oper Order",$lognote,$user_data);
		
		return true;
	}
	
	public function update_orderTicketNo($data,$adminuser)
	{
		
		
		$updatdata=array(
			"TotalCost" => $data["TotalCost"]
		);
		
		$this->db->where('OrderNo ', $data["Orderno"]);
		$this->db->where('AgentCode ', $adminuser["uadmin_account"]);
		$this->db->update('map_order', $updatdata); 
		
		
		//插入客人信息表bok_cps
		$iPassenger=count($data['passengerID']);
		for($i=0;$i< $iPassenger;$i++)
		{
			$book_cpsdata=array(
				"HKID" => $data["HKID"][$i]
			);
			
			$this->db->where('PassengerID ', $data["passengerID"][$i]);
			$this->db->update('bok_cps', $book_cpsdata);
		}
		//记录日志
		return true;
	}
	
	//检查是否有票号
	public function checkTicketNo($sOrderno)
	{
		$sql="Select Count(*) As CountHK From bok_cps Where OrderNo='$sOrderno' And HKID=''";
		
		$query=$this->db->query($sql);
		
		
		return $query->row()->CountHK;
		
		
		
	}
	
	//写订单日志
	public function write_orderlog($orderno,$OperNote,$Note,$user)
	{
		//产生订单号
		ini_set("date.timezone","Asia/Shanghai");
		$now = date('Y-m-d H:i:s');
		
		if($OperNote=="writelog")
		{
			$logtype="私有日志";
		}
		else
		{
			$logtype="公开日志";	
		}
		$data=array(
			"OperNote"	=> $OperNote,
			"OperDate"     => $now,
			"OperAccount"  => $user["user_account"],
			"OperAccName"  => $user["user_name"],
			"AgentCode"    => $user["AgentCode"],
			"AgentName"    => $user["AgentName"],
			"OrderNo"      => $orderno,
			"Note"         => $Note,
			"logtype"      => $logtype
		);
		return $this->db->insert('his_orderoperlog', $data); 
	}
	
	//获取订单日志
	public function getOrderlog($orderno,$limitType="")
	{
		$this->db->where("OrderNo",$orderno);
		if($limitType!="")
		{
			$this->db->where("logtype",$limitType);
		}
		$this->db->order_by("Operdate desc");
		$query=$this->db->get('his_orderoperlog');
		return $query->result();
	}
	
}